package web

import (
	"context"
	"encoding/xml"
	"github.com/kataras/iris/v12/mvc"
	"io/ioutil"
	"micro-grpc-server/app/http/controllers"
	pb "micro-grpc-server/services/wechat/proto"
)

type WechatController struct {
	controllers.Controller
	WechatClient pb.WechatService
}

func (c *WechatController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("POST", "{scenario:string}/robot", "Robot")
}

// Robot 众测活动的 wechat 接收脚本
func (c *WechatController) Robot(scenario string, ctx context.Context) string {
	var robotRequest = &pb.WechatReplyRequest{Scenario: scenario}
	// 读取query参数
	if err := c.Ctx.ReadQuery(robotRequest.Query); err != nil {
		return ""
	}
	if robotRequest.Query.EncryptType == "aes" {
		// 读取加密参数
		if err := xml.NewDecoder(c.Ctx.Request().Body).Decode(robotRequest.EncryptedXMLMsg); err != nil {
			return ""
		}
	} else {
		rawXMLMsgBytes, err := ioutil.ReadAll(c.Ctx.Request().Body)
		if err != nil {
			return ""
		}
		if err := xml.Unmarshal(rawXMLMsgBytes, &robotRequest.Body); err != nil {
			return ""
		}
	}
	resp, err := c.WechatClient.RobotReply(ctx, robotRequest)
	if err != nil {
		return ""
	}
	return resp.Result
}
